package com.zyk.util;

import com.zyk.leetcode.TreeNode;

/**
 * @author zhangsan
 * @date 2021/4/9 15:01
 */
public class TreeUtil {

    /** 按照下标生成树, 父节点 = i; 左孩子 = i * 2 + 1; 右孩子 = i*2+2, null也得传 */
    public static TreeNode generateTreeByArr(Integer[] treeInfo) {
        return generateByIndex(treeInfo, 0);
    }

    // 左节点: i*2+1, 右节点: i*2+2
    private static TreeNode generateByIndex(Integer[] treeInfo, int i) {
        if (i >= treeInfo.length || treeInfo[i] == null) {
            return null;
        }

        TreeNode root = new TreeNode(treeInfo[i]);
        root.left = generateByIndex(treeInfo, i * 2 + 1);
        root.right = generateByIndex(treeInfo, i * 2 + 2);
        return root;
    }


    /**
     * ============print============
     */
    public static void prePrint(TreeNode root) {
        prePrintProcess(root);
        System.out.println();
    }

    private static void prePrintProcess(TreeNode root) {
        if (root == null) {
            return;
        }
        System.out.print(root.val + " ");
        prePrintProcess(root.left);
        prePrintProcess(root.right);
    }

}
